<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 14-6-8
 * Time: 下午7:55
 */

namespace Macaca\Module;

use Macaca;
use Monkey;

class Token {

    public /**
     * @var \Monkey\App
     */
        $app;

    /**
     * @param Monkey\App $app
     */
    public function __construct($app) {
        $this->app = $app;
    }

    /**
     * 获取一个新的token
     * @param string $key
     * @return string
     */
    public function grantToken($key = '') {
        $token = md5($key . session_id() . $this->app->TIME);
        $token = implode(array_reverse(str_split($token)));
        $key = $this->getTokenKey($key);
        $_SESSION[$key] = $token;
        return $token;
    }

    /**
     * 验证一个token
     * @param $token
     * @param string $key
     * @return bool
     */
    public function checkToken($token, $key = '') {
        $key = $this->getTokenKey($key);

        if (!isset($_SESSION[$key])) {
            return false;
        }

        $token = $_SESSION[$key];
        unset($_SESSION[$key]);
        return $token and $token == $token;
    }

    private function getTokenKey($key) {
        return 'token_' . $key;
    }

} 